package com.flower.wing.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SocketServer implements Runnable {
	ServerSocket serverSocket;
	Thread[] threadArr;
	Connection dbConn;

	public SocketServer(int cnt, int port, Connection conn) {
		try {
			
			dbConn = conn;
			// 서버 소켓을 생성하여 7777번 포트와 바인딩.
			serverSocket = new ServerSocket(port);
			System.out.println(getTime() + " 서버가 준비되었습니다.");

			threadArr = new Thread[cnt];
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void start() {
		for (int i = 0; i < threadArr.length; i++) {
			threadArr[i] = new Thread(this);
			threadArr[i].start();
		}
	}

	@Override
	public void run() {
		DataHandler dataHandler = new DataHandler();
		while (true) {
			try {
				String secondDate = new SimpleDateFormat("yyMMddhhmmss").format(new java.util.Date()); //전송받은 시간
				System.out.println(getTime() + " 가 연결 요청을 기다립니다.");
				Socket socket = serverSocket.accept();
				System.out.println(getTime() + " " + socket.getInetAddress()
						+ "로부터 연결요청이 들어왔습니다.");
				try{
					BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //전송된 데이터 읽기
					while(true){
						String str = reader.readLine();
						if (str == null){
							break;
						} else {
							str = str + "," + secondDate;
							dataHandler.InputDB(str, dbConn); //데이터베이스에 데이터 저장
						}
						System.out.println(str);
						
					}
				} catch (IOException e){
					System.out.println(e.getMessage());
				}
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	static String getTime() {
		String name = Thread.currentThread().getName();
		SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]");
		return f.format(new Date()) + name;
	}
}
